package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.TreeDownloadFiles;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.FilesSizeType;
import cn.cdeden.knowledge.domain.vo.PersonalFilesTreeVo;
import cn.cdeden.knowledge.enums.DeleteTypeEnums;
import cn.cdeden.knowledge.enums.MinioTypeEnum;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.mapper.FilesCollectionMapper;
import cn.cdeden.knowledge.utils.FileUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.knowledge.utils.SetCollectionDataUtil;
import cn.cdeden.resource.api.RemoteOssEsService;
import cn.cdeden.resource.api.domain.RemoteEsFilesTree;
import cn.cdeden.system.api.RemoteDictService;
import cn.cdeden.system.api.RemoteDifyService;
import cn.cdeden.system.api.RemoteExpertAppService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.bo.RemoteDifyCreateByFileBo;
import cn.cdeden.system.api.domain.bo.RemoteExpertAppBo;
import cn.cdeden.system.api.domain.vo.RemoteDifyCreateByFileVo;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import io.seata.spring.annotation.GlobalTransactional;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.redisson.api.RedissonClient;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cdeden.knowledge.mapper.PersonalFilesTreeMapper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.service.PersonalFilesTreeService;
@Service
@RequiredArgsConstructor
public class PersonalFilesTreeServiceImpl extends ServiceImpl<PersonalFilesTreeMapper, PersonalFilesTree> implements PersonalFilesTreeService{

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;

    @DubboReference(check = false)
    private final RemoteOssEsService remoteOssEsService;

    @DubboReference(check = false)
    private final RemoteExpertAppService remoteExpertAppService;

    private final RemoteDifyService remoteDifyService;

    private final PersonalFilesTreeMapper mapper;

    private final FilesCollectionMapper filesCollectionMapper;

//    private final PersonalFilesTreeService fileService;
    private final RedissonClient redissonClient;


    public static final String ku = "personalFileLibrary-";

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public PersonalFilesTreeVo selectTree(PersonalFilesTreeParam query) throws BadRequestException {
        LoginUser loginUser = LoginHelper.getLoginUser();
        String username = loginUser.getUsername();
        String userId = Long.toString(loginUser.getUserId());
        if (StringUtils.isNotEmpty(query.getType()) && StringUtils.equalsIgnoreCase(query.getType(), "11")) {
//            FileUserDto userDto = FileUserUtils.getUser(username);//用户信息
            RemoteUserVo userDto = remoteUserService.selectUserByUserName(username);
            //校验权限
            username = userDto.getUserName();
            userId = Long.toString(userDto.getUserId());
        }
        query.setUserId(userId);
        query.setUsername(username);

        PersonalFilesTree parentTree = getPersonalFilesTree(query.getParentId(), userId); //父树信息

        if (StringUtils.isEmpty(query.getParentId())) {
            query.setParentId(String.valueOf(parentTree.getId()));
        }

        List<PersonalFilesTree> trees = mapper.selectTree(query);

        List<PersonalFilesTreeVo> vos = MapstructUtils.convert(trees, PersonalFilesTreeVo.class);
        PersonalFilesTreeVo convert = MapstructUtils.convert(parentTree, PersonalFilesTreeVo.class);
        convert.setChildren(vos);

        //给用户生成minio桶名
        RemoteUserVo remoteUserVo = remoteUserService.selectUserByUserId(loginUser.getUserId());
        if (!StringUtils.isNotBlank(remoteUserVo.getMinioBucket())) {
            //生成minio桶名
            String minioBucket = MinioTypeEnum.PERSON.getType() + "-" + loginUser.getUsername() + "-" + loginUser.getUserId();
            remoteUserService.updateMinioBucket(minioBucket, remoteUserVo.getUserId());
        }

        return convert;
    }

    @Override
    public PersonalFilesTree getPersonalFilesTree(String parentId, String id) {
        PersonalFilesTree parentTree = null;
        if (StringUtils.isEmpty(parentId)) {
            parentTree = this.createTree(id);
        } else {
            LambdaQueryWrapper<PersonalFilesTree> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PersonalFilesTree::getId, parentId)
                .eq(PersonalFilesTree::getCreateId, id)
                .isNull(PersonalFilesTree::getDeleteId);
            ;
            parentTree = this.getOne(wrapper);
            if (parentTree == null) {
                throw new RuntimeException("非法的父类编号或文件夹已被删除");
            }
        }
        return parentTree;
    }

    @Override
    public PersonalFilesTree createTree(String id) {
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>();
        queryWrapper.eq("real_name", "个人库")
            .eq("parent_id", ku + id)
            .eq("path", "/个人库");
        PersonalFilesTree filesTree = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(filesTree)) {
            filesTree = new PersonalFilesTree();
            filesTree.setRealName("个人库");
//            filesTree.setSuperiorsPath();
            filesTree.setType(TreeTypeEnum.HEAD.getType());
            filesTree.setPath("/" + filesTree.getRealName());
            filesTree.setParentId(ku + id);
//            filesTree.setCreateBy(username);
            filesTree.setCreateId(id);
            filesTree.setCreateTime(new Date());
            this.save(filesTree);
            Long treeId = filesTree.getId();
            filesTree.setTopParentId(String.valueOf(treeId));
            this.updateById(filesTree);
        } else {
            String topParentId = filesTree.getTopParentId();
            if (StringUtils.isBlank(topParentId)) {
                Long treeId = filesTree.getId();
                filesTree.setTopParentId(String.valueOf(treeId));
                this.updateById(filesTree);
                organizeData(filesTree);
            }
        }
        return filesTree;

    }

    @Override
    public void organizeData(PersonalFilesTree filesTree) {
        Long parentId = filesTree.getId();
        LambdaQueryWrapper<PersonalFilesTree> queryWrapper = new LambdaQueryWrapper<PersonalFilesTree>()
            .eq(PersonalFilesTree::getParentId, parentId)
            .orderByDesc(PersonalFilesTree::getCreateTime);
        List<PersonalFilesTree> list = this.list(queryWrapper);

        String superiorsIds = filesTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = String.valueOf(parentId);
        } else {
            superiorsIds += "," + parentId;
        }

        for (PersonalFilesTree tree : list) {
            tree.setTopParentId(filesTree.getTopParentId());

            tree.setSuperiorsIds(superiorsIds);
            this.updateById(tree);
            if (StringUtils.equalsIgnoreCase(tree.getType(), TreeTypeEnum.FILE.getType())) { //文件
                upDateFolderSize(tree, FilesSizeType.AddSize);
            } else { //文件夹
                organizeData(tree);
            }
        }
    }

    @Override
    public boolean upDateFolderSize(PersonalFilesTree filesTree, String type) {
        if (ObjectUtils.isEmpty(filesTree)) {
            return false;
        }
//        if(StringUtils.equalsIgnoreCase(filesTree.getType(),TreeTypeEnum.FILE.getType())){ //文件
        String superiorsIds = filesTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = superiorFolderCheck(filesTree);
        }
        List<String> fatherIds = new ArrayList<>(Arrays.asList(superiorsIds.split(",")));
        int i = 0;
        Long size = filesTree.getSize();
        if (ObjectUtils.isEmpty(size)) {
            return true;
        }
        if (CollectionUtils.isEmpty(fatherIds)) {
            return false;
        }
        if (StringUtils.equalsIgnoreCase(type, FilesSizeType.AddSize)) {
            i = mapper.upDateFolderSizeSum(fatherIds, size);
        } else if (StringUtils.equalsIgnoreCase(type, FilesSizeType.DeleteSize)) {
            ;
            i = mapper.upDateFolderSizeLess(fatherIds, size);
        }
        return i > 0;
    }

    @Override
    public String superiorFolderCheck(PersonalFilesTree filesTree) {
        //        if (ObjectUtils.isEmpty(filesTree)){
//            throw new RuntimeException("错误的文件编号");
//        }
        String parentId = filesTree.getParentId();
        Stack<String> stack = new Stack<>();
        stack.push(parentId);
//
        Set<String> strings = new HashSet<>();

        while (!stack.isEmpty()) {
            String pop = stack.pop();
            strings.add(pop);
            if (pop.contains(ku)) {
                break;
            }
            QueryWrapper<PersonalFilesTree> wrapper = new QueryWrapper<PersonalFilesTree>().eq("id", pop);
            PersonalFilesTree tree = this.getOne(wrapper);
            String storageId = tree.getStorageId();
            if (StringUtils.isNotBlank(storageId)) {
                strings.addAll(Arrays.asList(storageId.split(",")));
                break;
            }
            stack.push(tree.getParentId());

        }
        StringJoiner joiner = new StringJoiner(",");
        for (String string : strings) {
            if (string.contains(ku)) {
                continue;
            }

            joiner.add(string);
        }


        return joiner.toString();
    }

    @Override
    public TableDataInfo<PersonalFilesTreeVo> selectTreePage(PersonalFilesTreeParam query, Pageable pageable) {
        query.setStatus(true);  //设置只查询没有删除的数据
        String parentId = query.getParentId();
        String realName = query.getRealName();
        String userId = query.getUserId();
        if (StringUtils.isNotBlank(realName)) {
            query.setParentId(null);   //需不需要 查当前文件夹的 内容
            IPage<PersonalFilesTree> queryPage = PageUtil.toMybatisPage(pageable);
            QueryWrapper<PersonalFilesTree> predicate = getSelectGenerate(query, userId, parentId);

        }
        IPage<PersonalFilesTree> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<PersonalFilesTree> personalFilesTreeIPage = mapper.selectTree(query, queryPage);
        TableDataInfo<PersonalFilesTree> build = TableDataInfo.build(personalFilesTreeIPage);
        return MapstructUtils.convertTableDataInfo(build, PersonalFilesTreeVo.class);
    }

    @Override
    public PersonalFilesTree createFolder(String parentId, String folderName, LoginUser user) throws BadRequestException {
        return this.createFolder(parentId, folderName, user, true);
    }

    @Override
    public Boolean JudgmentEmpty(List<String> ids, String parentId) {
        if (ids.contains(parentId)) {
            return true;
        }
        HashSet<String> setId = new HashSet<>();
        folderCheck(ids, setId, true);
        if (setId.contains(parentId)) {
            return true;
        }
        return false;
    }

    @Override
    public Long folderCheck(List<String> ids) {
        Set<String> setId = new HashSet<>();
        List<String> idList = new ArrayList<>();
        if (ids.size()!=0){
            QueryWrapper<PersonalFilesTree> wrapper = new QueryWrapper<PersonalFilesTree>().in("id", ids).isNull("delete_id");
            List<PersonalFilesTree> list = this.list(wrapper);
            list.forEach(file -> {
                if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FILE.getType(), file.getType())) {
                    setId.add(String.valueOf(file.getId()));
                } else {
                    idList.add(String.valueOf(file.getId()));
                }
            });
        }

        /*
         * SELECT  id,top_parent_id,superiors_ids,parent_id,real_name,suffix,superiors_path,path,type,storage_id,edition_name,edition,storage_type,linking_state,size,collection,attention,remarks,create_id,create_by,create_time,update_id,update_by,update_time,delete_id,delete_by,delete_time,delete_type,file_md5,sys,doc_content  FROM personal_files_tree     WHERE (id IN () AND delete_id IS NULL)
         *
         * */


        folderCheck(idList, setId, true);

        if (CollectionUtils.isNotEmpty(setId)) {
            QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("IFNULL(sum(size),0) as totalScore")
                .in("id", setId);
            Map<String, Object> map = this.getMap(queryWrapper);
            BigDecimal sumCount = (BigDecimal) map.get("totalScore");
            return sumCount.longValue();
        }
        return 0L;
    }

    @Override
    public Boolean judgeIsEmpty(String userId, String username, String folderName, String parentId, String type, String suffix) {
        return judgeIsEmpty(null, userId, username, folderName, parentId, type, suffix);
    }


    @Override
    public Boolean judgeIsEmpty(String id, String userId, String username, String folderName, String parentId, String type, String suffix) {
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
            .eq("create_id", userId).eq("create_by", username)
            .eq("parent_id", parentId).eq("real_name", folderName)
            .isNull("delete_id");
        queryWrapper.eq("type", TreeTypeEnum.find(type).getType());
        if (StringUtils.isNotEmpty(suffix)) {
            queryWrapper.eq("suffix", suffix);
        }
        if (StringUtils.isNotEmpty(id)) {
            queryWrapper.eq("id", id);
        }

        List<PersonalFilesTree> list = this.list(queryWrapper);
        return CollectionUtils.isEmpty(list);
    }

    @Override
    public boolean updatePath(String userId, String username, String path, String newPath, String id, boolean b) {
        UpdateWrapper<PersonalFilesTree> update = new UpdateWrapper<>();
        int length = path.length();
        List<String> list = new ArrayList<>();
        list.add(id);
        Set<String> objects = folderSon(list);
        update.setSql("path=INSERT(path,1," + length + ",'" + newPath + "')")
            .setSql("superiors_path=INSERT(superiors_path,1," + length + ",'" + newPath + "')");
        if (b) {
            update.set("delete_id", null).set("delete_by", null).set("delete_time", null).set("delete_type", null);
        }
        update.set("update_id", userId).set("update_by", username).set("update_time", new Date())
            .likeRight("path", path)
            .eq("create_id", userId).ne("id", id).isNull("delete_id")
        ;
        if (CollectionUtils.isNotEmpty(objects)) {
            update.in("id", objects);
        }


        return update(update);
    }


    @Override
    public Set<String> folderSon(List<String> ids) {
        if (CollectionUtils.isEmpty(ids) || ids.size() <= 0) {
            return new HashSet<>();
        }

        Set<String> strings = new HashSet<>();
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>().in("parent_id", ids);

        List<PersonalFilesTree> list = this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> list1 = new ArrayList<>();
            list.forEach(tree -> {
                if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), tree.getType())) {
                    list1.add(String.valueOf(tree.getId()));
                }
                strings.add(String.valueOf(tree.getId()));
            });
            if (CollectionUtils.isNotEmpty(list1)) {
                strings.addAll(folderSon(list1));
            }
//            throw new BadRequestException("选中的文件夹中有子级，无法删除");
        }

        return strings;
    }


    /**
     * @param ids
     * @param setId
     * @param b
     * @return void
     * @author Yu.
     * @Description // 文件下的所有文件
     * @Date 2022/10/14 15:51
     **/
    public void folderCheck(List<String> ids, Set<String> setId, boolean b) {
        if (CollectionUtils.isEmpty(ids) || ids.size() <= 0) {
            return;
        }

//        ArrayList<String> ids = new ArrayList<>(setId);
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>().in("parent_id", ids);
        if (b) {
            queryWrapper.isNull("delete_id");
        } else {
            queryWrapper.isNotNull("delete_id").eq("delete_type", DeleteTypeEnums.NO_DISPLAY.getType());
        }
        List<PersonalFilesTree> list = this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> list1 = new ArrayList<>();
            list.forEach(tree -> {
                if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), tree.getType())) {
                    list1.add(String.valueOf(tree.getId()));
                }
                setId.add(String.valueOf(tree.getId()));
            });
            folderCheck(list1, setId, b);
//            throw new BadRequestException("选中的文件夹中有子级，无法删除");
        }
    }

    @Override
    //事务报错
    @GlobalTransactional
    public void calculateSpaceSize(String userId) {
        //是否计算空间    // 还有错误的文件夹路径
        List<PersonalFilesTree> list = this.lambdaQuery()
            .eq(PersonalFilesTree::getType,TreeTypeEnum.FILE.getType())
            .eq(StringUtils.isNotBlank(userId),PersonalFilesTree::getCreateId,userId)
            .list();
        if (CollectionUtils.isNotEmpty(list)){
            Map<String, List<PersonalFilesTree>> listMap = list.stream().collect(
                Collectors.groupingBy(PersonalFilesTree::getCreateId)
            );
//            List<User> userList = new ArrayList<>();
            List<RemoteUserVo> userList = new ArrayList<>();
            Map<String, Long> map = new HashMap<>();
            listMap.forEach((k,v)->{
                userList.add(RemoteUserVo.builder()
                    .userId(Long.valueOf(k))
                    .storageUse(v.stream().mapToLong(PersonalFilesTree::getSize).sum())
                    .build());
            });
            remoteUserService.updateBatchById(userList);
//            userService.updateBatchById(userList);
        }
    }

    @Override
    public boolean upDateFolderSizeUpDate(PersonalFilesTree filesTree, Long originalSize, Long newSize) {
        String superiorsIds = filesTree.getSuperiorsIds();
        List<String> fatherIds = new ArrayList<>(Arrays.asList(superiorsIds.split(",")));
        return mapper.upDateFolderSizeUpDate(fatherIds, originalSize, newSize) > 0;
    }

    @Override
    public TableDataInfo<FilesTree> selectPersonalTreePage(SearchFilesInfoDto infoDto, Pageable pageable) {
        IPage queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FilesTree> treeIPage = mapper.selectPersonalTreePage(infoDto, queryPage);
        return TableDataInfo.build(treeIPage);
    }

    @Override
    public IPage<PersonalFilesTree> selectPersonalTreePage(PersonalFilesTreeParam query, String createId, Pageable pageable) {
        List<String> sortDesc = query.getSortDesc();
        List<String> sortAsc = query.getSortAsc();
        if (CollectionUtils.isEmpty(sortDesc) && CollectionUtils.isEmpty(sortAsc)) {
            sortDesc = new ArrayList<>();
            sortDesc.add("type");
            sortDesc.add("create_time");
        }

        String parentId = query.getParentId();
        String realName = query.getRealName();
        if (StringUtils.isNotBlank(realName)) {
            query.setParentId(null);   //需不需要 查当前文件夹的 内容
            IPage<PersonalFilesTree> queryPage = PageUtil.toMybatisPage(pageable);
            QueryWrapper<PersonalFilesTree> predicate = getSelectGenerate(query, createId, parentId);
            return mapper.selectPage(queryPage, predicate);
        }
        QueryWrapper<PersonalFilesTree> predicate = getSelectGenerate(query, createId, null);
        IPage<PersonalFilesTree> personalFilesTreeIPage = new Page<>();
        personalFilesTreeIPage.setRecords(this.list(predicate));
        return personalFilesTreeIPage;
    }

    @Override
    public List<PersonalFilesTree> selectPersonalTree(String parentId) {
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
            .eq("parent_id", parentId).isNull("delete_id")
            .orderByDesc("create_time")
//                .orderBy(true,true,"type")
            ;
        return this.list(queryWrapper);
    }

    @Override
    public List<PersonalFilesTree> selectPersonalTree(PersonalFilesTreeParam query, String createId) {
        List<String> sortDesc = query.getSortDesc();
        List<String> sortAsc = query.getSortAsc();
        if (CollectionUtils.isEmpty(sortDesc) && CollectionUtils.isEmpty(sortAsc)) {
            sortDesc = new ArrayList<>();
            sortDesc.add("type");
            sortDesc.add("create_time");
        }

        QueryWrapper<PersonalFilesTree> predicate = getSelectGenerate(query, createId, null);

        return this.list(predicate);
    }

    @Override
    public boolean selectByNodeIdIsOwn(List<String> nodeId, String userId, boolean b) {
        Long count = this.lambdaQuery()
            .eq(PersonalFilesTree::getCreateId, userId)
            .and(true, e -> {
                e.eq(PersonalFilesTree::getType, TreeTypeEnum.FOLDER.getType())
                    .or()
                    .eq(PersonalFilesTree::getType, TreeTypeEnum.HEAD.getType());
            })
            .in(PersonalFilesTree::getId, nodeId)
            .isNull(PersonalFilesTree::getDeleteId)
            .count();
        if (count < nodeId.size()) {
            if (b){
                return true;
            }
            throw new RuntimeException("注意：您当前尝试访问的文件夹不属于您的账户。请确认您正在查找的文件夹路径或联系管理员获取更多帮助。");
        }
        return true;
    }

    @Override
    public List<PersonalFilesTree> selectJuniorAll(List<String> ids, String deleteType) {
        return mapper.selectJuniorAll(ids,deleteType);
    }

    @Override
    public List<TreeDownloadFiles> folderSonFiles(List<String> ids, Boolean b) {
        if (CollectionUtils.isEmpty(ids) || ids.size() <= 0) {
            return new ArrayList<>();
        }
        List<PersonalFilesTree> trees1 = selectFilesTree(ids);
        List<TreeDownloadFiles> filesList = MapstructUtils.convert(trees1, TreeDownloadFiles.class);
//        List<TreeDownloadFiles> filesList = ConvertUtil.convertList(trees1, TreeDownloadFiles.class);

        String join = Joiner.on(",").join(ids);
        List<PersonalFilesTree> trees = mapper.selectAllSubordinate(join,trees1.get(0).getCreateId(), b);

        List<TreeDownloadFiles> filesTrees = MapstructUtils.convert(trees, TreeDownloadFiles.class);
        //不要树结构
        boolean b1 = filesTrees.addAll(filesList);
//
//        //list转树结构
//        List<TreeDownloadFiles> treeList = TreeDownloadFiles.listToTerr(filesTrees, ids, "personal");

        return filesTrees;
    }



    @Override
    public List<PersonalFilesTree> selectFilesTree(List<String> ids) {
        QueryWrapper<PersonalFilesTree> predicate = new QueryWrapper<>();
        predicate.in("id", ids)
//                .eq("type",TreeTypeEnum.FILE.getType())
            .isNull("delete_id")
        ;

        return this.list(predicate);
    }

    @Override
    public PersonalFilesTree selectByParentId(String parentId) {
        return mapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, Long.valueOf(parentId)));
    }

    @Override
    public List<PersonalFilesTree> selectByParentIdAll(String parentId) {
        List<PersonalFilesTree> personalFilesTrees = mapper.selectList(new LambdaQueryWrapper<PersonalFilesTree>()
            .eq(PersonalFilesTree::getParentId, parentId)
            .eq(PersonalFilesTree::getType, "file"));
        return personalFilesTrees;
    }

    @Override
    public boolean insertOne(PersonalFilesTree personalFilesTree) {
        return mapper.insertOrUpdate(personalFilesTree);
    }

    @Override
    public PersonalFilesTree selectById(String moduleId) {
        return mapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getId, Long.valueOf(moduleId)));
    }

    @Override
    public List<PersonalFilesTree> selectByIds(List<String> idList) {
        return mapper.selectList(new LambdaQueryWrapper<PersonalFilesTree>().in(PersonalFilesTree::getId, idList));
    }

    @Override
    public boolean updatePathID(String userId, String username, String path, String superiorsIds, String newPath, String newSuperiorsIds, String id, boolean b) {
        //修改儿子路径 //和上级的id
        UpdateWrapper<PersonalFilesTree> update = new UpdateWrapper<>();
        int length = path.length();
        int length1 = superiorsIds.length();
        List<String> list = new ArrayList<>();
        list.add(id);
        Set<String> objects = folderSon(list);
        update.setSql("path=INSERT(path,1," + length + ",'" + newPath + "')")
            .setSql("superiors_path=INSERT(superiors_path,1," + length + ",'" + newPath + "')")
            .setSql("superiors_ids=INSERT(superiors_ids,1," + length1 + ",'" + newSuperiorsIds + "')")
            .likeRight("path", path)
            .likeRight("superiors_ids", superiorsIds)
            .eq("create_id", userId)
            .ne("id", id);
        if (CollectionUtils.isNotEmpty(objects)) {
            update.in("id", objects);
        }
        return update(update);
    }

    @Override
    public PersonalFilesTree createFolderFilePath(String parentId, String path,LoginUser user) {
        String[] split = path.split("/");
        PersonalFilesTree  tree = null;
        for (String folderName : split) {
            tree = createFolder(parentId, folderName, user, false);
            parentId = String.valueOf(tree.getId());
        }
        return tree;
    }

    @Override
//    @Lock4j(name = "personal:", keys = {"#uploadDto.parentId"}, acquireTimeout = 40000, expire = 40000)
    public PersonalFilesTree createFolderFilePath(LoginUser user, FilesTreeUploadDto uploadDto) {
        String parentId = uploadDto.getParentId();
        String id = String.valueOf(user.getUserId());
        String filePath = uploadDto.getFilePath();
        PersonalFilesTree parentTree = new PersonalFilesTree();
        if (StringUtils.isNotBlank(filePath)) {           // 判断是否需要建立文件夹
            parentTree = this.getPersonalFilesTree(parentId, id);
            //创建文件夹
            parentTree = this.createFolderFilePath(parentId, filePath, user);
            parentId = String.valueOf(parentTree.getId());
            uploadDto.setParentId(parentId);
        }
        PersonalFilesTree convert = MapstructUtils.convert(uploadDto, PersonalFilesTree.class);
        return convert;
    }

    @Override
    public List<PersonalFilesTree> selectByParentIdFolder(String parentId, String filePath) {
        String[] split = filePath.split("/");
        //根据parentId和路径数组 一层一层的查询到最后一层的文件夹的所有数据
        String lowId = null;
        for (int i = 0; i < split.length; i++) {
            PersonalFilesTree personalFilesTree = mapper.selectOne(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getParentId, parentId).eq(PersonalFilesTree::getRealName, split[i]));
            parentId = personalFilesTree.getId().toString();
            lowId = personalFilesTree.getId().toString();
        }
        //查询出文件夹中的所有文件
        return mapper.selectList(new LambdaQueryWrapper<PersonalFilesTree>().eq(PersonalFilesTree::getParentId, lowId).eq(PersonalFilesTree::getType, "file"));
    }

    @Override
    public FilesTree selectPersonalSuperiorFolder(String id, String userId, List<String> sort) throws BadRequestException {

        //获取文件是否存在
        PersonalFilesTree oneTree = this.lambdaQuery()
            .eq(PersonalFilesTree::getId, id)
            .eq(PersonalFilesTree::getCreateId, userId)
            .isNull(PersonalFilesTree::getDeleteId)
            .one();
        if (oneTree == null) {
            throw new BadRequestException("非法的编号或文件夹已被删除");
        }

        String[] split = oneTree.getSuperiorsIds().split(",");
        List<String> list = Arrays.asList(split);
        //获取文件上级节点信息
        List<FilesTree> filesTrees = mapper.selectPersonalSuperiorFolder(list, userId,sort);
//        //获取头节点
        PersonalFilesTree personalFilesTree = getPersonalFilesTree(null, userId);
        FilesTree convert = MapstructUtils.convert(personalFilesTree, FilesTree.class);
        filesTrees.add(convert);
//        //构建文件为树结构
        List<FilesTree> filesTrees1 = FilesTree.listToTerr(filesTrees, Arrays.asList(String.valueOf(personalFilesTree.getId())), "personal");

        FilesTree filesTree = filesTrees1.get(0);
        return filesTree;
//        return ConvertUtil.convert(filesTree, FilesTree.class);
    }

    @Override
    public int selectByIdTreePageInfo(String userId, String treeId, String parentId, Integer size, List<String> sort) {
        return mapper.selectByIdTreePageInfo(userId, treeId, parentId, size, sort);
    }

    @Override
    public List<PersonalFilesTree> getAllChildById(Long id) {
        mapper.getAllChildById(id);
        return null;
    }

    @Override
    public PersonalToEnterpriseDto assembleTeamToEnterprise(String id) {
        PersonalFilesTree filesTree = this.getById(id);

        PersonalToEnterpriseDto personalToEnterpriseDto = MapstructUtils.convert(filesTree, PersonalToEnterpriseDto.class);
        List<PersonalFilesTree> list = this.lambdaQuery().eq(PersonalFilesTree::getParentId, filesTree.getId()).list();
        //添加子级
        for (PersonalFilesTree file : list) {
            PersonalToEnterpriseDto toEnterpriseDto = assembleTeamToEnterprise(String.valueOf(file.getId()));
            if (toEnterpriseDto != null){
                personalToEnterpriseDto.getChildren().add(toEnterpriseDto);
            }
        }
        return personalToEnterpriseDto;
    }

    @Override
    public void fileToExpertApp(ToExpertAppDto toExpertAppDto) throws BadRequestException {
        //检查当前用户是否拥有专家知识库
        RemoteExpertAppBo remoteExpertApp = remoteExpertAppService.getRemoteExpertApp();
        if (remoteExpertApp == null) {
            throw new BadRequestException("当前未拥有于专家知识库，请先申请！");
        }

        //先判断是文件还是文件夹
        if (toExpertAppDto.getType().equals("file")) {
            fileToDify(toExpertAppDto.getFileIds());
        } else {
            folderToDify(toExpertAppDto.getFileIds());
        }
    }

    @Override
    public void againFileToExpertApp(ToExpertAppDto toExpertAppDto) {
        //先判断是文件还是文件夹
        if (toExpertAppDto.getType().equals("file")) {
            againFileToDify(toExpertAppDto.getFileIds());
        } else {
            againFolderToDify(toExpertAppDto.getFileIds());
        }
    }

    /**
     * 重新上传文件
     * @param fileIds
     */
    public void againFileToDify(List<Long> fileIds) {
        checkSize(fileIds);

        //查询用户的专家知识库id
        LoginUser loginUser = LoginHelper.getLoginUser();
        RemoteExpertAppBo remoteExpertAppBo = remoteExpertAppService.getDataBaseIdByUserId(loginUser.getUserId());
        String aiDatasetId = remoteExpertAppBo.getWikiIds();

        for(Long id: fileIds) {
            //查询单个文件的信息
            PersonalFilesTree personalFilesTree = mapper.selectById(id);
            RemoteDifyCreateByFileBo remoteDifyCreateByFileBo = new RemoteDifyCreateByFileBo();
            remoteDifyCreateByFileBo.setIndexing_technique("high_quality");
            RemoteDifyCreateByFileBo.ProcessingRule processingRule = new RemoteDifyCreateByFileBo.ProcessingRule();
            remoteDifyCreateByFileBo.setProcess_rule(processingRule);
            RemoteDifyCreateByFileBo.ProcessingRule.Rules rules = new RemoteDifyCreateByFileBo.ProcessingRule.Rules();
            processingRule.setRules(rules);
            processingRule.setMode("custom");
            ArrayList<RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule> preProcessingRules = new ArrayList<>();
            rules.setPre_processing_rules(preProcessingRules);
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_extra_spaces", true));
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_urls_emails", true));
            rules.setSegmentation(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.Segmentation("###", 500));
            String fileDatasetId = null;
            try {
                remoteDifyService.delete(aiDatasetId, personalFilesTree.getFileDatasetId());
                RemoteDifyCreateByFileVo byFile = remoteDifyService.createByFile(personalFilesTree.getStorageId(), personalFilesTree.getRealName(), aiDatasetId, remoteDifyCreateByFileBo);
                fileDatasetId = byFile.getDocument().getId();
                PersonalFilesTree personalFilesTree1 = new PersonalFilesTree();
                personalFilesTree1.setId(id);
                personalFilesTree1.setExpert("true");
                personalFilesTree1.setFileDatasetId(fileDatasetId);
                mapper.updateById(personalFilesTree1);
            } catch (Exception e) {
                throw new RuntimeException("文件上传到dify失败:网络错误或者文件重名或者文件格式错误或者该知识库已被删除");
            }
        }

    }

    /**
     * 重新上传文件夹
     * @param fileIds
     */
    public void againFolderToDify(List<Long> fileIds) {
        //查询该文件夹下所有的文件
        PersonalToEnterpriseDto personalToEnterpriseDto = this.assembleTeamToEnterprise(fileIds.get(0).toString());

        List<PersonalToEnterpriseDto> children = personalToEnterpriseDto.getChildren();
        children = children.stream().filter(personalToEnterpriseDto1 ->
            (personalToEnterpriseDto1.getSuffix().equals("txt") ||
                personalToEnterpriseDto1.getSuffix().equals("pdf") ||
                personalToEnterpriseDto1.getSuffix().equals("html") ||
                personalToEnterpriseDto1.getSuffix().equals("md") ||
                personalToEnterpriseDto1.getSuffix().equals("markdown") ||
                personalToEnterpriseDto1.getSuffix().equals("xlsx") ||
                personalToEnterpriseDto1.getSuffix().equals("xls") ||
                personalToEnterpriseDto1.getSuffix().equals("docx") ||
                personalToEnterpriseDto1.getSuffix().equals("csv") ||
                personalToEnterpriseDto1.getSuffix().equals("htm")) && personalToEnterpriseDto1.getDeleteId()== null)
            .collect(Collectors.toList());
        List<Long> ids = children.stream().map(personalToEnterpriseDto1 -> personalToEnterpriseDto1.getId()).collect(Collectors.toList());
        checkSize(ids);
        //查询用户的专家知识库id
        LoginUser loginUser = LoginHelper.getLoginUser();
        RemoteExpertAppBo remoteExpertAppBo = remoteExpertAppService.getDataBaseIdByUserId(loginUser.getUserId());
        String aiDatasetId = remoteExpertAppBo.getWikiIds();

        for (Long id : ids) {
            //查询单个文件的信息
            PersonalFilesTree personalFilesTree = mapper.selectById(id);
            RemoteDifyCreateByFileBo remoteDifyCreateByFileBo = new RemoteDifyCreateByFileBo();
            remoteDifyCreateByFileBo.setIndexing_technique("high_quality");
            RemoteDifyCreateByFileBo.ProcessingRule processingRule = new RemoteDifyCreateByFileBo.ProcessingRule();
            remoteDifyCreateByFileBo.setProcess_rule(processingRule);
            RemoteDifyCreateByFileBo.ProcessingRule.Rules rules = new RemoteDifyCreateByFileBo.ProcessingRule.Rules();
            processingRule.setRules(rules);
            processingRule.setMode("custom");
            ArrayList<RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule> preProcessingRules = new ArrayList<>();
            rules.setPre_processing_rules(preProcessingRules);
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_extra_spaces", true));
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_urls_emails", true));
            rules.setSegmentation(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.Segmentation("###", 500));
            String fileDatasetId = null;
            try {
                RemoteDifyCreateByFileVo byFile = remoteDifyService.createByFile(personalFilesTree.getStorageId(), personalFilesTree.getRealName(), aiDatasetId, remoteDifyCreateByFileBo);
                fileDatasetId = byFile.getDocument().getId();
                PersonalFilesTree personalFilesTree1 = new PersonalFilesTree();
                personalFilesTree1.setId(id);
                personalFilesTree1.setExpert("true");
                personalFilesTree1.setFileDatasetId(fileDatasetId);
                mapper.updateById(personalFilesTree1);
                remoteDifyService.delete(aiDatasetId, personalFilesTree.getFileDatasetId());
            } catch (Exception e) {
                throw new RuntimeException("文件上传到dify失败:网络错误或者文件重名或者文件格式错误或者该知识库已被删除");
            }
        }

    }


    /**
     * 上传的是文件类型
     * @param fileIds
     */
    public void fileToDify(List<Long> fileIds) {

        checkSize(fileIds);

        //查询用户的专家知识库id
        LoginUser loginUser = LoginHelper.getLoginUser();
        RemoteExpertAppBo remoteExpertAppBo = remoteExpertAppService.getDataBaseIdByUserId(loginUser.getUserId());
        String aiDatasetId = remoteExpertAppBo.getWikiIds();

        for(Long id: fileIds) {
            //查询单个文件的信息
            PersonalFilesTree personalFilesTree = mapper.selectById(id);
            RemoteDifyCreateByFileBo remoteDifyCreateByFileBo = new RemoteDifyCreateByFileBo();
            remoteDifyCreateByFileBo.setIndexing_technique("high_quality");
            RemoteDifyCreateByFileBo.ProcessingRule processingRule = new RemoteDifyCreateByFileBo.ProcessingRule();
            remoteDifyCreateByFileBo.setProcess_rule(processingRule);
            RemoteDifyCreateByFileBo.ProcessingRule.Rules rules = new RemoteDifyCreateByFileBo.ProcessingRule.Rules();
            processingRule.setRules(rules);
            processingRule.setMode("custom");
            ArrayList<RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule> preProcessingRules = new ArrayList<>();
            rules.setPre_processing_rules(preProcessingRules);
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_extra_spaces", true));
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_urls_emails", true));
            rules.setSegmentation(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.Segmentation("###", 500));
            String fileDatasetId = null;
            try {
                RemoteDifyCreateByFileVo byFile = remoteDifyService.createByFile(personalFilesTree.getStorageId(), personalFilesTree.getRealName(), aiDatasetId, remoteDifyCreateByFileBo);
                fileDatasetId = byFile.getDocument().getId();
                PersonalFilesTree personalFilesTree1 = new PersonalFilesTree();
                personalFilesTree1.setId(id);
                personalFilesTree1.setExpert("true");
                personalFilesTree1.setFileDatasetId(fileDatasetId);
                mapper.updateById(personalFilesTree1);
            } catch (Exception e) {
                throw new RuntimeException("文件上传到dify失败:网络错误或者文件重名或者文件格式错误或者该知识库已被删除");
            }
        }
    }

    /**
     * 上传的是文件夹类型（选择为文件夹时只能上传一个文件夹）
     * @param fileIds
     */
    public void folderToDify(List<Long> fileIds) {
        //查询该文件夹下所有的文件
//        PersonalToEnterpriseDto personalToEnterpriseDto = this.assembleTeamToEnterprise(fileIds.get(0).toString());
        List<String> collect = fileIds.stream().map(String::valueOf).collect(Collectors.toList());
        List<TreeDownloadFiles> treeDownloadFiles = this.folderSonFiles(collect, false);
        treeDownloadFiles = treeDownloadFiles.stream().filter(treeDownloadFiles1 -> treeDownloadFiles1.getType().equals("file")).collect(Collectors.toList());
        PersonalFilesTree personalFilesTree2 = new PersonalFilesTree();
        personalFilesTree2.setId(fileIds.get(0));
        personalFilesTree2.setExpert("true");
        mapper.updateById(personalFilesTree2);

//        List<PersonalToEnterpriseDto> children = personalToEnterpriseDto.getChildren();


        treeDownloadFiles = treeDownloadFiles.stream()
            .filter(personalToEnterpriseDto1 ->
                personalToEnterpriseDto1.getSuffix().equals("txt") ||
                    personalToEnterpriseDto1.getSuffix().equals("pdf") ||
                    personalToEnterpriseDto1.getSuffix().equals("html") ||
                    personalToEnterpriseDto1.getSuffix().equals("md") ||
                    personalToEnterpriseDto1.getSuffix().equals("markdown") ||
                    personalToEnterpriseDto1.getSuffix().equals("xlsx") ||
                    personalToEnterpriseDto1.getSuffix().equals("xls") ||
                    personalToEnterpriseDto1.getSuffix().equals("docx") ||
                    personalToEnterpriseDto1.getSuffix().equals("csv") ||
                    personalToEnterpriseDto1.getSuffix().equals("htm"))
            .collect(Collectors.toList());
        List<Long> ids = treeDownloadFiles.stream().map(personalToEnterpriseDto1 -> personalToEnterpriseDto1.getId()).collect(Collectors.toList());
        checkSize(ids);
        //查询用户的专家知识库id
        LoginUser loginUser = LoginHelper.getLoginUser();
        RemoteExpertAppBo remoteExpertAppBo = remoteExpertAppService.getDataBaseIdByUserId(loginUser.getUserId());
        String aiDatasetId = remoteExpertAppBo.getWikiIds();

        for (Long id : ids) {
            //查询单个文件的信息
            PersonalFilesTree personalFilesTree = mapper.selectById(id);
            RemoteDifyCreateByFileBo remoteDifyCreateByFileBo = new RemoteDifyCreateByFileBo();
            remoteDifyCreateByFileBo.setIndexing_technique("high_quality");
            RemoteDifyCreateByFileBo.ProcessingRule processingRule = new RemoteDifyCreateByFileBo.ProcessingRule();
            remoteDifyCreateByFileBo.setProcess_rule(processingRule);
            RemoteDifyCreateByFileBo.ProcessingRule.Rules rules = new RemoteDifyCreateByFileBo.ProcessingRule.Rules();
            processingRule.setRules(rules);
            processingRule.setMode("custom");
            ArrayList<RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule> preProcessingRules = new ArrayList<>();
            rules.setPre_processing_rules(preProcessingRules);
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_extra_spaces", true));
            preProcessingRules.add(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.PreProcessingRule("remove_urls_emails", true));
            rules.setSegmentation(new RemoteDifyCreateByFileBo.ProcessingRule.Rules.Segmentation("###", 500));
            String fileDatasetId = null;
            try {
                RemoteDifyCreateByFileVo byFile = remoteDifyService.createByFile(personalFilesTree.getStorageId(), personalFilesTree.getRealName(), aiDatasetId, remoteDifyCreateByFileBo);
                fileDatasetId = byFile.getDocument().getId();
                PersonalFilesTree personalFilesTree1 = new PersonalFilesTree();
                personalFilesTree1.setId(id);
                personalFilesTree1.setExpert("true");
                personalFilesTree1.setFileDatasetId(fileDatasetId);
                mapper.updateById(personalFilesTree1);
            } catch (Exception e) {
                throw new RuntimeException("文件上传到dify失败:网络错误或者文件重名或者文件格式错误或者该知识库已被删除");
            }
        }

    }

    public void checkSize(List<Long> ids) {
        List<PersonalFilesTree> personalFilesTreeList = mapper.selectList(new LambdaQueryWrapper<PersonalFilesTree>().in(PersonalFilesTree::getId, ids));
        List<PersonalFilesTree> personalFilesTrees = personalFilesTreeList
            .stream()
            .filter(personalFilesTree -> personalFilesTree.getSize() > 15728640)
            .collect(Collectors.toList());
        if (!personalFilesTrees.isEmpty()) {
            throw new RuntimeException("上传的文件中，文件的大小有超过15M的！");
        }
    }





    /**
     * @Description // 生成查询条件
     **/
    private QueryWrapper<PersonalFilesTree> getSelectGenerate(PersonalFilesTreeParam query, String createId, String parentId) {
        QueryWrapper<PersonalFilesTree> predicate = QueryHelpMybatisPlus.getPredicate(query);
        predicate.eq("create_id", createId)
            .isNull("delete_id")
        ;
        if (parentId != null) predicate.ne("id", parentId);

        return predicate;
    }


    /**
     * @Description // 获取关注和收藏信息
     **/
    private List<PersonalFilesTree> getInfo(List<PersonalFilesTree> trees) {
        if (ObjectUtils.isNotEmpty(trees)) {
            SetCollectionDataUtil setCollectionDataUtil = new SetCollectionDataUtil(filesCollectionMapper);
//            SetAttentionDataUtil setAttentionDataUtil = new SetAttentionDataUtil(filesAttentionMapper);
            trees = setCollectionDataUtil.setCollectionPersonalData(trees);//获取收藏
//            trees = setAttentionDataUtil.setAttentionPersonalData(trees);//获取关注
        }
        return trees;

    }


    private PersonalFilesTree createFolder(String parentId, String folderName, LoginUser user, boolean b){
        String username = user.getUsername();
        String id = Long.toString(user.getUserId());
        PersonalFilesTree parentTree = getPersonalFilesTree(parentId, id); //父树信息
        parentId = Long.toString(parentTree.getId());

        String superiorsIds = parentTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = parentId;
        } else {
            superiorsIds += "," + parentId;
        }
        if (StringUtils.isBlank(folderName)) {
            throw new RuntimeException("文件夹名不可为空");
        }
        folderName = FileUtil.fileNameProcessingException(folderName); //处理特殊符号处理  静态处理
        PersonalFilesTree filesTree = this.judgmentIsEmpty(null, id, username, folderName, parentId, TreeTypeEnum.FOLDER.getType(), null);
        if (ObjectUtils.isNotEmpty(filesTree)) {
            if (b) {
                throw new RuntimeException("文件夹名称重复");
            } else {
                return filesTree;
            }
        }

        PersonalFilesTree tree = new PersonalFilesTree(id, username);
        tree.setRealName(folderName);
        tree.setType(TreeTypeEnum.FOLDER.getType());
        tree.setParentId(parentId);
        tree.setPath(parentTree.getPath() + "/" + folderName);
        tree.setSuperiorsPath(parentTree.getPath());
        tree.setSuperiorsIds(superiorsIds);
        tree.setTopParentId(parentTree.getTopParentId());
        int insert = mapper.insert(tree);

        RemoteEsFilesTree remoteEsFilesTree = new RemoteEsFilesTree();
        remoteEsFilesTree.setId(tree.getId());
        remoteEsFilesTree.setSuperiorsIds(tree.getSuperiorsIds());
        remoteEsFilesTree.setParentId(tree.getParentId());
        remoteEsFilesTree.setSuffix(tree.getSuffix());
        remoteEsFilesTree.setRealName(tree.getRealName());
        remoteEsFilesTree.setType(tree.getType());
        remoteEsFilesTree.setStorageId(tree.getStorageId());
        remoteEsFilesTree.setSize(tree.getSize());
        remoteEsFilesTree.setVersionName(tree.getEditionName());
        remoteEsFilesTree.setVersionId(tree.getEdition());
        remoteEsFilesTree.setCreateBy(user.getUserId());
        remoteEsFilesTree.setCreateTime(new Date());
        remoteEsFilesTree.setUpdateBy(user.getUserId());
        remoteEsFilesTree.setUpdateTime(new Date());
        remoteEsFilesTree.setLibraryType(OssModuleType.Personal.getCode());
        remoteEsFilesTree.setUserIdList(Arrays.asList(String.valueOf(user.getUserId())));

        try {
            String insert1 = remoteOssEsService.insert(remoteEsFilesTree);
            PersonalFilesTree personalFilesTree = new PersonalFilesTree();
            personalFilesTree.setEsId(insert1);
            personalFilesTree.setId(tree.getId());
            baseMapper.updateById(personalFilesTree);
        } catch (Exception e) {

        }




//        boolean save = mapper.save(tree);
        if (insert > 0) {
            return tree;
        } else {
            return null;
        }
    }

    public PersonalFilesTree judgmentIsEmpty(String id, String userId, String username, String folderName, String parentId, String type, String suffix) {
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
            .eq("create_id", userId).eq("create_by", username)
            .eq("parent_id", parentId).eq("real_name", folderName)
            .isNull("delete_id");
        queryWrapper.eq("type", TreeTypeEnum.find(type).getType());
        if (StringUtils.isNotEmpty(suffix)) {
            queryWrapper.eq("suffix", suffix);
        }
        if (StringUtils.isNotEmpty(id)) {
            queryWrapper.eq("id", id);
        }
        List<PersonalFilesTree> list = this.list(queryWrapper);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }
}
